/**
  ******************************************************************************
  * File Name          : freertos.c
  * Description        : Code for freertos applications
  ******************************************************************************
  * This notice applies to any and all portions of this file
  * that are not between comment pairs USER CODE BEGIN and
  * USER CODE END. Other portions of this file, whether 
  * inserted by the user or by software development tools
  * are owned by their respective copyright owners.
  *
  * Copyright (c) 2018 STMicroelectronics International N.V. 
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without 
  * modification, are permitted, provided that the following conditions are met:
  *
  * 1. Redistribution of source code must retain the above copyright notice, 
  *    this list of conditions and the following disclaimer.
  * 2. Redistributions in binary form must reproduce the above copyright notice,
  *    this list of conditions and the following disclaimer in the documentation
  *    and/or other materials provided with the distribution.
  * 3. Neither the name of STMicroelectronics nor the names of other 
  *    contributors to this software may be used to endorse or promote products 
  *    derived from this software without specific written permission.
  * 4. This software, including modifications and/or derivative works of this 
  *    software, must execute solely and exclusively on microcontroller or
  *    microprocessor devices manufactured by or for STMicroelectronics.
  * 5. Redistribution and use of this software other than as permitted under 
  *    this license is void and will automatically terminate your rights under 
  *    this license. 
  *
  * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" 
  * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT 
  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
  * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY
  * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT 
  * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 
  * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF 
  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "FreeRTOS.h"
#include "task.h"
#include "cmsis_os.h"

/* USER CODE BEGIN Includes */     
#include <string.h>
#include "stm32f0xx.h"
#include "gdata.h"
#include "usart.h"
#include "dht11.h"
#include "tim.h"
#include "iwdg.h"
/* USER CODE END Includes */

/* Variables -----------------------------------------------------------------*/
osThreadId defaultTaskHandle;
osThreadId tsk_pm2_5Handle;
osThreadId tsk_dht11Handle;
osThreadId tsk_485Handle;
osThreadId tsk_espHandle;
osThreadId tsk_ctrlHandle;
osThreadId tsk_inputHandle;
osSemaphoreId sem_esp_serialHandle;
osSemaphoreId sem_485Handle;
osSemaphoreId sen_pm2_5_1Handle;
osSemaphoreId sem_pm2_5_2Handle;
osSemaphoreId sem_outputHandle;

/* USER CODE BEGIN Variables */

/* USER CODE END Variables */

/* Function prototypes -------------------------------------------------------*/
void StartDefaultTask(void const * argument);
void entry_pm2_5(void const * argument);
void entry_dht11(void const * argument);
void entry_485(void const * argument);
void entry_esp(void const * argument);
void entry_ctrl(void const * argument);
void entry_input(void const * argument);

void MX_FREERTOS_Init(void); /* (MISRA C 2004 rule 8.1) */

/* USER CODE BEGIN FunctionPrototypes */

/* USER CODE END FunctionPrototypes */

/* Hook prototypes */

/* Init FreeRTOS */

void MX_FREERTOS_Init(void) {
  /* USER CODE BEGIN Init */
       
  /* USER CODE END Init */

  /* USER CODE BEGIN RTOS_MUTEX */
  /* add mutexes, ... */
  /* USER CODE END RTOS_MUTEX */

  /* Create the semaphores(s) */
  /* definition and creation of sem_esp_serial */
  osSemaphoreDef(sem_esp_serial);
  sem_esp_serialHandle = osSemaphoreCreate(osSemaphore(sem_esp_serial), 1);

  /* definition and creation of sem_485 */
  osSemaphoreDef(sem_485);
  sem_485Handle = osSemaphoreCreate(osSemaphore(sem_485), 1);

  /* definition and creation of sen_pm2_5_1 */
  osSemaphoreDef(sen_pm2_5_1);
  sen_pm2_5_1Handle = osSemaphoreCreate(osSemaphore(sen_pm2_5_1), 1);

  /* definition and creation of sem_pm2_5_2 */
  osSemaphoreDef(sem_pm2_5_2);
  sem_pm2_5_2Handle = osSemaphoreCreate(osSemaphore(sem_pm2_5_2), 1);

  /* definition and creation of sem_output */
  osSemaphoreDef(sem_output);
  sem_outputHandle = osSemaphoreCreate(osSemaphore(sem_output), 1);

  /* USER CODE BEGIN RTOS_SEMAPHORES */
  osSemaphoreWait(sem_esp_serialHandle,osWaitForever);

  /* add semaphores, ... */
  /* USER CODE END RTOS_SEMAPHORES */

  /* USER CODE BEGIN RTOS_TIMERS */
  /* start timers, add new ones, ... */
  /* USER CODE END RTOS_TIMERS */

  /* Create the thread(s) */
  /* definition and creation of defaultTask */
  osThreadDef(defaultTask, StartDefaultTask, osPriorityNormal, 0, 64);
  defaultTaskHandle = osThreadCreate(osThread(defaultTask), NULL);

  /* definition and creation of tsk_pm2_5 */
  osThreadDef(tsk_pm2_5, entry_pm2_5, osPriorityHigh, 0, 128);
  tsk_pm2_5Handle = osThreadCreate(osThread(tsk_pm2_5), NULL);

  /* definition and creation of tsk_dht11 */
  osThreadDef(tsk_dht11, entry_dht11, osPriorityNormal, 0, 128);
  tsk_dht11Handle = osThreadCreate(osThread(tsk_dht11), NULL);

  /* definition and creation of tsk_485 */
  osThreadDef(tsk_485, entry_485, osPriorityIdle, 0, 128);
  tsk_485Handle = osThreadCreate(osThread(tsk_485), NULL);

  /* definition and creation of tsk_esp */
  osThreadDef(tsk_esp, entry_esp, osPriorityNormal, 0, 128);
  tsk_espHandle = osThreadCreate(osThread(tsk_esp), NULL);

  /* definition and creation of tsk_ctrl */
  osThreadDef(tsk_ctrl, entry_ctrl, osPriorityHigh, 0, 128);
  tsk_ctrlHandle = osThreadCreate(osThread(tsk_ctrl), NULL);

  /* definition and creation of tsk_input */
  osThreadDef(tsk_input, entry_input, osPriorityRealtime, 0, 128);
  tsk_inputHandle = osThreadCreate(osThread(tsk_input), NULL);

  /* USER CODE BEGIN RTOS_THREADS */
  /* add threads, ... */
  /* USER CODE END RTOS_THREADS */

  /* USER CODE BEGIN RTOS_QUEUES */
  /* add queues, ... */
  /* USER CODE END RTOS_QUEUES */
}

/* StartDefaultTask function */
void StartDefaultTask(void const * argument)
{

  /* USER CODE BEGIN StartDefaultTask */
  char buf[24] = "hello uart 485 test";
  /* Infinite loop */
  for(;;)
  {
	switch(g_ir_state)
	{
		case IR_IDLE:
			HAL_GPIO_WritePin(TEST_LED_GPIO_Port,TEST_LED_Pin,GPIO_PIN_RESET);
			break;
		case CAPTURE_START:
				HAL_GPIO_TogglePin(TEST_LED_GPIO_Port,TEST_LED_Pin);
				osDelay(800);
			break;
		case CAPTURE_RUNNING:
		case IR_SENDING:
			for(int i=0;i<10;i++)
			{
				HAL_GPIO_TogglePin(TEST_LED_GPIO_Port,TEST_LED_Pin);
				osDelay(50);
			}
			g_ir_state = IR_IDLE;
			break;
		case CAPTURE_FINISHED:
			for(int i=0;i<3;i++)
			{
				HAL_GPIO_TogglePin(TEST_LED_GPIO_Port,TEST_LED_Pin);
				osDelay(1000);
			}
			g_ir_state = IR_IDLE;
			break;
		osDelay(100);
	}
  }
  /* USER CODE END StartDefaultTask */
}

/* entry_pm2_5 function */
void entry_pm2_5(void const * argument)
{
  /* USER CODE BEGIN entry_pm2_5 */
  /* Infinite loop */
  for(;;)
  {	
	HAL_UART_Receive_DMA(&huart4,u4Buff,256);
	osSemaphoreWait(sem_pm2_5_2Handle,osWaitForever);
	if(u4Buff[0] != 0XAA || u4Buff[9] != 0xAB) continue;
	if(u4Len != 10) continue;
	g_pm25 = u4Buff[2]|u4Buff[3]<<8;
	g_pm10 = u4Buff[4]|u4Buff[5]<<8;
    //SEGGER_RTT_printf(0,"pm25:[%d]\n",g_pm25);	
    osDelay(10);
  }
  /* USER CODE END entry_pm2_5 */
}

/* entry_dht11 function */
void entry_dht11(void const * argument)
{
  /* USER CODE BEGIN entry_dht11 */
  /* Infinite loop */
  for(;;)
  {
	  DHT11_Get_HT(&g_humi1,&g_temp1,DHT_DATA1_GPIO_Port,DHT_DATA1_Pin);
	  osDelay(1000);
	  DHT11_Get_HT(&g_humi2,&g_temp2,DHT_DATA2_GPIO_Port,DHT_DATA2_Pin);
	  osDelay(1000);
//	  SEGGER_RTT_printf(0,"%d %d %d %d\n",(int)(g_humi1*10),\
//		  (int)(g_humi2*10),(int)(g_temp1*10),(int)(g_temp2*10));
  }
  /* USER CODE END entry_dht11 */
}

/* entry_485 function */
void entry_485(void const * argument)
{
  /* USER CODE BEGIN entry_485 */
  /* Infinite loop */
  for(;;)
  {
	  osDelay(1000);
  }
  /* USER CODE END entry_485 */
}

/* entry_esp function */
void entry_esp(void const * argument)
{
  /* USER CODE BEGIN entry_esp */
  uint8_t check = 0;
  uint8_t len = 0;
  /* Infinite loop */
  for(;;)
  {	 	  
	  HAL_UART_Receive_DMA(&huart6,u6Buff,256);
	  osSemaphoreWait(sem_esp_serialHandle,osWaitForever);
	  //cal check
	  if(u6Buff[0] != 0x33) continue;
	  if(u6Buff[u6Len-1] != 0x44) continue;
	  check = 0;
	  len = u6Buff[1];
	  for(uint8_t i=1;i<len+2;i++)
		check += u6Buff[i];
	  if(check != u6Buff[u6Len-2]) continue;
	  switch(u6Buff[2])
	  {
		  case 1://ctrl switch
			  Relay_Ctrl(u6Buff[4],u6Buff[3]);
			  break;
		  case 2://record 
		      g_flash_record.number = u6Buff[3];
		      g_flash_record.pulse = 0;
			  g_capture_flag = 1;
			  g_ir_state = CAPTURE_START;
			  SEGGER_RTT_printf(0,"ready to capture\n");
			  HAL_NVIC_EnableIRQ(IR_RECV_EXTI_IRQn);
			  break;
		  case 3://load
				IR_Send_Code(u6Buff[3]);
			break;
		  case 4://send encoded ir code
			break;
	  }
      osDelay(10);
  }
  /* USER CODE END entry_esp */
}

/* entry_ctrl function */
void entry_ctrl(void const * argument)
{
  /* USER CODE BEGIN entry_ctrl */
	//osDelay(20000);
  /* Infinite loop */
  for(;;)
  {
	//generate json frame.
	  memset(esp_send_buff,0,sizeof(esp_send_buff));
	  sprintf(esp_send_buff,"{\"pm2.5\":\"%d\",\"pm10\":\"%d\",\"temperature\":[\"%.1f\",\"%.1f\"],\"humidity\":[\"%.1f\",\"%.1f\"],\
\"state\":[\"%d\",\"%d\",\"%d\",\"%d\",\"%d\"],\"output\":[\"%d\",\"%d\",\"%d\",\"%d\",\"%d\"]}",
	  g_pm25,g_pm10,g_temp1,g_temp2,g_humi1,g_humi2,
	  BIT(g_key,0),BIT(g_key,1),BIT(g_key,2),BIT(g_key,3),BIT(g_key,4),
	  BIT(g_out,0),BIT(g_out,1),BIT(g_out,2),BIT(g_out,3),BIT(g_out,4));
	  HAL_UART_Transmit(&huart6,(uint8_t*)esp_send_buff,strlen(esp_send_buff),1000);
      osDelay(1000);
  }
  /* USER CODE END entry_ctrl */
}

/* entry_input function */
void entry_input(void const * argument)
{
  /* USER CODE BEGIN entry_input */
  /* Infinite loop */
  for(;;)
  {
	  Get_Key_State();
	  osDelay(10);
	  HAL_IWDG_Refresh(&hiwdg);
  }
  /* USER CODE END entry_input */
}

/* USER CODE BEGIN Application */
     
/* USER CODE END Application */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
